package com.rightsidetech.http.controller.storeApp.trade;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.mall.entity.MallIntegralCommodity;
import com.rightsidetech.mall.service.MallIntegralCommodityService;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralDetialReq;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralReq;
import com.rightsidetech.system.dtos.response.store.StoreAppIntegralResp;
import com.rightsidetech.system.entity.SysAgentInfo;
import com.rightsidetech.system.entity.SysCompanyArea;
import com.rightsidetech.system.entity.store.SysStoreAccountInfo;
import com.rightsidetech.system.entity.store.SysStoreAddress;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.*;
import com.rightsidetech.trade.dtos.request.integral.IntegralOrderSaveReq;
import com.rightsidetech.trade.dtos.request.integral.IntegralSaveReq;
import com.rightsidetech.trade.dtos.response.integral.IntegralConvertRecordResp;
import com.rightsidetech.trade.dtos.response.integral.IntegralOrderDetailResp;
import com.rightsidetech.trade.service.TdIntegralOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.util.Date;

@RestController
@RequestMapping("/storeApp/integral")
@ShenyuSpringMvcClient(path = "/storeApp/integral/**")
@Api(tags = "门店积分相关")
public class TdIntegralOrderController extends BaseController {

    @Resource
    private TdIntegralOrderService tdIntegralOrderService;
    @Resource
    private MallIntegralCommodityService mallIntegralCommodityService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;
    @Resource
    private SysCompanyAreaService sysCompanyAreaService;
    @Resource
    private SysStoreIntegralService sysStoreIntegralService;
    @Resource
    private SysStoreAddressService sysStoreAddressService;


    @Log
    @Token
    @PostMapping("/save")
    @ApiOperation("积分商城下单")
    public ResponseData<String> save(@RequestBody IntegralOrderSaveReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallIntegralCommodity commodity = mallIntegralCommodityService.selectByPrimaryKey(req.getCommodityId());
        if(ObjectUtil.isEmpty(commodity)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到此积分商品");
        }
        if(commodity.getStock() <= 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此积分商品已售完");
        }
        SysStoreAddress address = sysStoreAddressService.selectByPrimaryKey(req.getAddressId());
        if(ObjectUtil.isEmpty(address)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到地址");
        }
        if(commodity.getCommodityStatus() != 3){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此积分商品未上架");
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if(ObjectUtil.isEmpty(storeInfo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到登录的门店");
        }
        if(!storeInfo.getId().equals(address.getStoreInfoId())){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"该地址不属于此门店");
        }
        SysAgentInfo agentInfo = sysAgentInfoService.selectSysAgentInfo(storeInfo.getSysAgentInfoId());
        if(ObjectUtil.isEmpty(agentInfo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找门店代理商");
        }
        SysCompanyArea area = sysCompanyAreaService.selectById(agentInfo.getAreaId());
        if(ObjectUtil.isEmpty(area)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到门店大区");
        }
        SysStoreAccountInfo accountInfo = sysStoreInfoService.selectByStoreId(storeInfo.getId());
        if(ObjectUtil.isEmpty(accountInfo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到门店对应的账户");
        }
        BigDecimal point = accountInfo.getPoint();
        if(point.compareTo(commodity.getPrice()) < 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"门店积分不足以兑换该积分商品");
        }
        IntegralSaveReq saveReq = new IntegralSaveReq();
        saveReq.setOrderNo(DateUtil.format(new Date(),"yyyyMMddHHMMss") + RandomUtil.randomInt(100,999));
        saveReq.setStoreName(storeInfo.getStoreName());
        saveReq.setStoreInfoId(storeInfo.getId());
        saveReq.setConnectWay(address.getStorePhone());
        saveReq.setAgentInfoId(storeInfo.getSysAgentInfoId());
        saveReq.setAgentName(agentInfo.getName());
        saveReq.setAreaName(area.getName());
        saveReq.setAreaId(area.getId());
        saveReq.setPrice(commodity.getPrice());
        saveReq.setIntegralCommodityId(commodity.getId());
        saveReq.setIntegralCommodityName(commodity.getCommodityName());
        saveReq.setIntegralCommoditySpecs(commodity.getSpecs());
        if(StringUtils.isEmpty(address.getDoorplate())){
            saveReq.setAddress(address.getAddress());
        }else{
            saveReq.setAddress(address.getAddress() + address.getDoorplate());
        }
        saveReq.setCover(commodity.getCover());
        saveReq.setNum(1);
        saveReq.setStatus((byte)1);
        saveReq.setAddressId(req.getAddressId());
        saveReq.setContact(address.getStoreName());
        saveReq.setUnderlinedPrice(commodity.getUnderlinedPrice());
        ResponseData<String> data = tdIntegralOrderService.saveOrder(saveReq);
        if(data.getCodeId() != 1){
            return data;
        }
        //扣除积分商品库存
        MallIntegralCommodity commodityRecord = new MallIntegralCommodity();
        commodityRecord.setId(commodity.getId());
        commodityRecord.setStock(commodity.getStock() - saveReq.getNum());
        mallIntegralCommodityService.updateByPrimaryKeySelective(commodityRecord);
        //扣除门店账户积分
        SysStoreAccountInfo accountRecord = new SysStoreAccountInfo();
        accountRecord.setPoint(accountInfo.getPoint().subtract(saveReq.getPrice()));
        accountRecord.setId(accountInfo.getId());
        sysStoreInfoService.updateAccountInfo(accountRecord);
        //添加积分记录表
        StoreCommodityIntegralDetialReq scdq = new StoreCommodityIntegralDetialReq();
        scdq.setCommodityName(commodity.getCommodityName());
        scdq.setBarCode(commodity.getSpecsCode());
        scdq.setSpecs(commodity.getSpecs());
        scdq.setIntegral(commodity.getPrice());
        scdq.setCommodityId(commodity.getId());
        StoreCommodityIntegralReq IntReq = new StoreCommodityIntegralReq();
        IntReq.setStoreId(storeInfo.getId());
        IntReq.setAccountId(accountInfo.getId());
        IntReq.setIntegral(saveReq.getPrice());
        IntReq.setOrderNo(saveReq.getOrderNo());
        IntReq.setList(CollUtil.newArrayList(scdq));
        sysStoreIntegralService.integralSave(IntReq);
        return data;
    }

//    @Log
//    @Token
//    @PostMapping("/pay")
//    @ApiOperation("积分订单确认兑换")
//    public ResponseData payOrder(@RequestBody IntegralPayReq req){
//        if(StrUtil.isBlank(req.getOrderNo())){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"订单号不可为空");
//        }
//        Long storeId = Long.parseLong(getAttribute());
//        TdIntegralOrder order = tdIntegralOrderService.selectByOrderNo(req.getOrderNo());
//        if(ObjectUtil.isEmpty(order)){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到订单");
//        }
//        if(!order.getStoreInfoId().equals(storeId)){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"该订单不属于该门店");
//        }
//        if(order.getStatus() == 1){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"该订单已完成");
//        }
//        SysStoreAccountInfo accountInfo = sysStoreInfoService.selectByStoreId(storeId);
//        if(ObjectUtil.isEmpty(accountInfo)){
//            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到该门店的账户");
//        }
//        if(accountInfo.getPoint().compareTo(order.getPrice()) < 0){
//            return ResponseData.fail("积分不足以支付此订单");
//        }
//        MallIntegralCommodity commodity = mallIntegralCommodityService.selectByPrimaryKey(order.getId());
//        if(ObjectUtil.isEmpty(commodity)){
//            return ResponseData.fail("未找到积分商品");
//        }
//        //扣除积分商品库存
//        MallIntegralCommodity commodityRecord = new MallIntegralCommodity();
//        commodityRecord.setId(commodity.getId());
//        commodityRecord.setStock(commodity.getStock() - order.getNum());
//        mallIntegralCommodityService.updateByPrimaryKeySelective(commodityRecord);
//        //扣除门店账户积分
//        SysStoreAccountInfo accountRecord = new SysStoreAccountInfo();
//        accountRecord.setPoint(accountInfo.getPoint().subtract(order.getPrice()));
//        accountRecord.setId(accountInfo.getId());
//        sysStoreInfoService.updateAccountInfo(accountRecord);
//        //添加积分记录表
//        StoreCommodityIntegralDetialReq scdq = new StoreCommodityIntegralDetialReq();
//        scdq.setCommodityName(commodity.getCommodityName());
//        scdq.setBarCode(commodity.getSpecsCode());
//        scdq.setSpecs(commodity.getSpecs());
//        scdq.setIntegral(commodity.getPrice());
//        scdq.setCommodityId(commodity.getId());
//        StoreCommodityIntegralReq IntReq = new StoreCommodityIntegralReq();
//        IntReq.setStoreId(storeId);
//        IntReq.setAccountId(accountInfo.getId());
//        IntReq.setIntegral(order.getPrice());
//        IntReq.setOrderNo(order.getOrderNo());
//        IntReq.setList(CollUtil.newArrayList(scdq));
//        sysStoreIntegralService.integralSave(IntReq);
//        TdIntegralOrder orderRecord = new TdIntegralOrder();
//        orderRecord.setId(order.getId());
//        orderRecord.setStatus((byte)1);
//        tdIntegralOrderService.updateByPrimaryKeySelective(orderRecord);
//        return ResponseData.success(CodeIdEnum.Success);
//    }

    @Log
    @Token
    @GetMapping("/my_integral")
    @ApiOperation("我的积分")
    public ResponseData<BigDecimal> myIntegral(){
        SysStoreAccountInfo accountInfo = sysStoreInfoService.selectByStoreId(Long.parseLong(getAttribute()));
        if(ObjectUtil.isEmpty(accountInfo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到门店对应的账户");
        }
        return ResponseData.success(accountInfo.getPoint());
    }

    @Log
    @Token
    @GetMapping("/convert")
    @ApiOperation("积分兑换记录")
    public ResponseData<PageInfo<IntegralConvertRecordResp>> convertRecord(PageRequest req){
        Long storeId = Long.parseLong(getAttribute());
        if (ObjectUtil.isEmpty(storeId)) {
            return ResponseData.fail("未找到登录人");
        }
        return tdIntegralOrderService.orderPage(req, storeId);
    }


    @Log
    @Token
    @GetMapping("/detail")
    @ApiOperation("积分明细")
    public ResponseData<PageInfo<StoreAppIntegralResp>> minutiae(PageRequest req){
        Long storeId = Long.parseLong(getAttribute());
        if (ObjectUtil.isEmpty(storeId)) {
            return ResponseData.fail("未找到登录人");
        }
        return sysStoreIntegralService.storeAppPage(req, storeId);
    }

    @Log
    @Token
    @GetMapping("/order_detail")
    @ApiOperation("订单详情")
    public ResponseData<IntegralOrderDetailResp> detail(@RequestParam(value = "id",required = false) Long id,@RequestParam(value = "orderNo",required = false) String orderNo){
        if(id == null && StrUtil.isBlank(orderNo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"订单id和订单号不可都为空");
        }
        ResponseData<IntegralOrderDetailResp> data = tdIntegralOrderService.orderDetail(id,orderNo);
        if(data.getCodeId() != 1){
            return data;
        }
        IntegralOrderDetailResp result = data.getResData();
        MallIntegralCommodity commodity = mallIntegralCommodityService.selectByPrimaryKey(result.getCommodityId());
        if(ObjectUtil.isNotEmpty(commodity)){
            result.setUnderlinedPrice(commodity.getUnderlinedPrice());
            result.setCommodityPrice(commodity.getPrice());
        }
        return ResponseData.success(result);
    }
}
